package sicnu.cs.ich.activity.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import sicnu.cs.ich.activity.domain.ActivityLike;
import sicnu.cs.ich.activity.service.IActivityLikeService;
import sicnu.cs.ich.api.common.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 黎琦
 * @date 2021/12/7 20:06
 **/
@Service
@RequiredArgsConstructor
public class ActivityLikeServieImpl implements IActivityLikeService {
    private final MongoTemplate mongoTemplate;

    @Override
    public void insert(ActivityLike activityLike) {
        mongoTemplate.save(activityLike);
    }

    @Override
    public Long updateByAid(Integer aid, Integer uid) {
        //添加用户id，并更新点赞数
        Query query = new Query(Criteria.where("aid").is(aid));
        Update update = new Update();
        update.addToSet("uidList", uid);
        update.inc("responseNum", 1);
        mongoTemplate.updateFirst(query, update, ActivityLike.class);
        //将互动点赞数返回
        ActivityLike activityLike = mongoTemplate.findOne(query, ActivityLike.class);
        assert activityLike != null;
        Long num = activityLike.getResponseNum();
        return num==null?0:num;
    }

    @Override
    public void updateCommentNumByAid(Integer aid){
        //更新评论数
        Query query = new Query(Criteria.where("aid").is(aid));
        Update update = new Update();
        update.inc("commentNum", 1);
        mongoTemplate.updateFirst(query, update, ActivityLike.class);
//        //将评论数返回
//        ActivityLike activityLike = mongoTemplate.findOne(query, ActivityLike.class);
//        assert activityLike != null;
//        Long num = activityLike.getCommentNum();
//        return num==null?0:num;
    }

    @Override
    public List<Map<Integer, Long>> allActivityCommentNumAndLikeNum() {
        List<ActivityLike> all = mongoTemplate.findAll(ActivityLike.class);
        //评论map
        Map<Integer, Long> map1 = new HashMap<>(Constants.ACTIVITY_INIT_NUM);
        //点赞map
        Map<Integer, Long> map2 = new HashMap<>(Constants.ACTIVITY_INIT_NUM);
        for (ActivityLike activityLike : all) {
            map1.put(activityLike.getAid(), activityLike.getCommentNum());
            map2.put(activityLike.getAid(), activityLike.getResponseNum());
        }
        List<Map<Integer, Long>> maps = new ArrayList<>();
        maps.add(map1);
        maps.add(map2);
        return maps;
    }
}
